package com.b2c.erp.controller.wms;

import com.b2c.entity.result.PagingResponse;
import com.b2c.common.utils.DateUtil;
import com.b2c.entity.ErpOrderItemEntity;
import com.b2c.entity.erp.vo.ErpStockOutGoodsListVo;
import com.b2c.entity.ErpStockOutFormEntity;
import com.b2c.entity.vo.ErpStockOutFormDetailVo;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.interfaces.wms.ErpGoodsStockLogsService;
import com.b2c.interfaces.wms.ErpStockOutFormService;
import com.b2c.interfaces.wms.StockLocationService;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.enums.erp.EnumGoodsStockLogType;

import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 描述：
 * 出库管理
 *
 * @author qlp
 * @date 2019-05-28 17:01
 */
@Controller
@RequestMapping("/stock_out")
public class    StockOutController {
    @Autowired
    private StockLocationService stockLocationService;
    @Autowired
    private ErpStockOutFormService erpStockOutFormService;
    @Autowired
    private ErpUserActionLogService logService;
    @Autowired
    private ErpGoodsStockLogsService goodsStockLogsService;

    /**
     * 拣货单list
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/from_list", method = RequestMethod.GET)
    public String pickingList(Model model, HttpServletRequest request) {
        String page = request.getParameter("page");
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(page)) {
            try {
                pageIndex = Integer.parseInt(page);
            } catch (Exception e) {
            }
        }
        String number = "";
        if(!StringUtils.isEmpty(request.getParameter("number"))){
            number = request.getParameter("number");
            model.addAttribute("number",number);
        }
        String sourceNo = "";
        if(!StringUtils.isEmpty(request.getParameter("sourceNo"))){
            sourceNo = request.getParameter("sourceNo");
            model.addAttribute("sourceNo",sourceNo);
        }


        String id = "0";
        if(!StringUtils.isEmpty(request.getParameter("id")) && request.getParameter("id").equals("null")==false){
            id = request.getParameter("id");
        }
        Integer status = null;
        if(!StringUtils.isEmpty(request.getParameter("status"))){
            try {
                status = Integer.parseInt(request.getParameter("status"));
            } catch (Exception e) {
            }
        }

        var result = erpStockOutFormService.getPickingList(pageIndex, pageSize, number,status,Long.parseLong(id),sourceNo);

        model.addAttribute("list", result.getList());
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        //添加系统日志
//        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Query,"/stock_out/picking_list","拣货单列表 , 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");

        model.addAttribute("view", "jhd");
        model.addAttribute("pView", "ck");
        model.addAttribute("ejcd", "出库");
        model.addAttribute("sjcd", "拣货单管理");
        return "order_goods_picking_list";
    }



    /**
     * 拣货单打印弹窗(合并sku数量)
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/picking_detail_print", method = RequestMethod.GET)
    public String pickingDetailPrint(Model model, HttpServletRequest request, @RequestParam Long id) {
        var form = erpStockOutFormService.getStockOutFormById(id);
        model.addAttribute("pick", form);

        var formItems = erpStockOutFormService.getStockOutFormItemListByFormId(id);
        model.addAttribute("goods", formItems);

        return "stock_out_picking_detail_print";
    }

//    /**
//     * 拣货单详情弹窗（确认拣货操作）
//     *
//     * @param model
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "/picking_detail", method = RequestMethod.GET)
//    public String pickingDetail(Model model, HttpServletRequest request) {
//        try {
//            Long id = Long.parseLong(request.getParameter("id"));
//            var form = erpStockOutFormService.getStockOutFormById(id);
//
//            model.addAttribute("pick", form);
//            //查询仓库
//            List<ErpStockLocationEntity> houses = stockLocationService.getListByParentId(0);
//            model.addAttribute("houses", houses);
//
////            model.addAttribute("goods", goods);
//        } catch (Exception e) {
//
//        }
//
//        return "stock_out_picking_detail";
//    }



    /**
     * 出库单
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/has_out_list", method = RequestMethod.GET)
    public String getStockInFrom(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = 20;
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }
        String number = "";
        if (!StringUtils.isEmpty(request.getParameter("billNo"))) number = request.getParameter("billNo");

        model.addAttribute("billNo", number);

        Integer outType = null;
        if (!StringUtils.isEmpty(request.getParameter("type"))) outType = Integer.parseInt(request.getParameter("type"));

        String startDate = request.getParameter("startDate");
        model.addAttribute("startDate", startDate);

        String endDate = request.getParameter("endDate");
        model.addAttribute("endDate", endDate);

        model.addAttribute("startDate", request.getParameter("startDate"));
        model.addAttribute("endDate", request.getParameter("endDate"));


        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        PagingResponse<ErpStockOutFormEntity> result = erpStockOutFormService.getStockOutFormList(pageIndex, pageSize,outType, number,  startDate, endDate);
        model.addAttribute("list", result.getList());
        model.addAttribute("totalSize", result.getTotalSize());

//        if(outType==null) {
            model.addAttribute("view", "stock_list");
            model.addAttribute("pView", "sj");
            model.addAttribute("ejcd", "出库");
            model.addAttribute("sjcd", "出库单列表");
//        }else if(outType == 2){
//            model.addAttribute("view", "cgthform");
//            model.addAttribute("pView", "cg");
//            model.addAttribute("sjcd", "出库单列表");
//        }
        return "wms/erp_stock_out_from_list";
    }


        /**
     * 出库详情（打印，弹窗）
     *
     * @param model
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/form_item", method = RequestMethod.GET)
    public String stockOutForm(Model model, @RequestParam Long id, HttpServletRequest request) {
        var detail = erpStockOutFormService.getErpStockOutFormDetailVo(id);

        if (detail != null) {
            model.addAttribute("detail", detail);


        } else {
            model.addAttribute("detail", new ErpStockOutFormDetailVo());
             }

        return "erp_stock_out_form_item";
    }

    /**
     * 拣货单商品列表
     * @param model
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/picking_goods_list", method = RequestMethod.GET)
    public String orderGoodsList(Model model, HttpServletRequest request, @RequestParam Long id) {

        List<ErpStockOutGoodsListVo> goodsList = erpStockOutFormService.getStockOutFormItemListByFormId(id);
        model.addAttribute("goodsList", goodsList);

        return "stock_out_picking_goods_list";
    }

    @RequestMapping(value = "/logs", method = RequestMethod.GET)
    public String stockInLogs(Model model, HttpServletRequest request) {
        Integer pageIndex = 1;
        Integer pageSize = DataConfigObject.getInstance().getPageSize();
        ;
        if (StringUtils.isEmpty(request.getParameter("page")) == false) {
            try {
                pageIndex = Integer.parseInt(request.getParameter("page"));
            } catch (Exception e) {
            }
        }
        Integer startTime = 0;
        Integer endTime = 0;
        String date = request.getParameter("date");
        if (StringUtils.isEmpty(date) == false) {
            //时间筛选了2020-02-07 - 2020-02-14
            String[] st = date.split(" - ");
            if (st.length > 0) {
                startTime = DateUtil.dateToStamp(st[0]);
            }
            if (st.length > 1) {
                endTime = DateUtil.dateTimeToStamp(st[1] + " 23:59:59");
            }

        }

        var result = goodsStockLogsService.getListByType(EnumGoodsStockLogType.OUT, 1, 50,startTime,endTime);

        model.addAttribute("list", result.getList());
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());

        model.addAttribute("view", "cgcklog");
        model.addAttribute("pView", "sj");
        model.addAttribute("ejcd", "出库");
        model.addAttribute("cgcklog", "出库记录");

        return "wms/stock_out_logs_list";
    }

    @ResponseBody
    @RequestMapping(value = "/stock_out_export", method = RequestMethod.GET)
    public void purchasePutDetail(Model model, HttpServletRequest req, HttpServletResponse response) {

        var lists = erpStockOutFormService.outList(req.getParameter("startTime"),req.getParameter("endTime"));//invoiceService.invoiceItemPOList();

        /***************根据店铺查询订单导出的信息*****************/
        String fileName = "stock_out_export_";//excel文件名前缀
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        //创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        //第一行为空
        row = sheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("");
        cell = row.createCell(0);
        cell.setCellValue("出库单号");
        cell = row.createCell(1);
        cell.setCellValue("商品编码");
        cell = row.createCell(2);
        cell.setCellValue("规格编码");
        cell = row.createCell(3);
        cell.setCellValue("数量");
        cell = row.createCell(4);
        cell.setCellValue("销售价");
        cell = row.createCell(5);
        cell.setCellValue("采购价");
        cell = row.createCell(6);
        cell.setCellValue("出库时间");


        int currRowNum = 0;
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 循环写入数据
        for (int i = 0; i < lists.size(); i++) {
            currRowNum++;
            //写入订单
            ErpOrderItemEntity itemVo = lists.get(i);
            //创建行
            row = sheet.createRow(currRowNum);
            cell = row.createCell(0);
            cell.setCellValue(itemVo.getStockOutNo());
            //商品名称
            cell = row.createCell(1);
            cell.setCellValue(itemVo.getProductNumber());
            cell = row.createCell(2);
            cell.setCellValue(itemVo.getSkuNumber());

            cell = row.createCell(3);
            cell.setCellValue(itemVo.getQuantity());
            //退货单号
            cell = row.createCell(4);
            cell.setCellValue(String.valueOf(itemVo.getItemAmount()));
            //规格
            cell = row.createCell(5);
            cell.setCellValue(String.valueOf(itemVo.getPurPrice()));
            cell = row.createCell(6);
            cell.setCellValue(DateUtil.stampToDateTime(itemVo.getPrintQty()));
        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((fileName + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }
    }

}
